import { logging } from 'protractor';
import { RepeatMode, PeriodicTask, PeriodicTaskParam } from './../../../model/task';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-peroidic-task-adder',
  templateUrl: './peroidic-task-adder.component.html',
  styleUrls: ['./peroidic-task-adder.component.less']
})
export class PeroidicTaskAdderComponent implements OnInit {
  taskForm: FormGroup;
  adderTags: string[] = [];
  tagInputVisible = false;
  tagInputValue = '';
  @ViewChild('inputElement', { static: false }) inputElement?: ElementRef;
  selectedRepeatMode: RepeatMode = 0;
  constructor(
    private fb: FormBuilder,
  ) {
    this.taskForm = this.fb.group({
      name: [null, Validators.required],
      target: [null, Validators.required],
      importance: [null, Validators.required],
      end: [null, Validators.required],
      repeatMode: [RepeatMode.preDay, Validators.required],
      repeatNum: [1, Validators.required],
      description: [],
      id: [],
    });
  }

  ngOnInit(): void {}

  handleAdderTagerClose(removedTag: string): void {
    this.adderTags = this.adderTags.filter(tag => tag !== removedTag);
  }

  sliceTagName(tag: string): string {
    const isLongTag = tag.length > 20;
    return isLongTag ? `${tag.slice(0, 20)}...` : tag;
  }

  showTagInput(): void {
    this.tagInputVisible = true;
    setTimeout(() => {
      this.inputElement?.nativeElement.focus();
    }, 10);
  }

  handleTagInputConfirm(): void {
    if (this.tagInputValue && this.adderTags.indexOf(this.tagInputValue) === -1) {
      this.adderTags = [...this.adderTags, this.tagInputValue];
    }
    this.tagInputValue = '';
    this.tagInputVisible = false;
  }

  handleRepeatModeChange(mode: RepeatMode): void {
    this.selectedRepeatMode = mode;
  }

  public setData(task?: PeriodicTask): void {
    if (task) {
      this.taskForm.setValue({
        name: task.name,
        target: task.target,
        importance: task.importance?.toString(),
        end: task.end,
        description: task.description,
        repeatMode: task.repeatMode,
        repeatNum: task.repeatNum,
        id: task.id,
      });
      this.adderTags = task.tags!.split(',');
      if (this.adderTags[0] === '') {
        this.adderTags = [];
      }

    }
  }

  public reset(): void {
    this.adderTags = [];
    this.tagInputValue = '';
    this.taskForm.reset();
  }

  public getData(): PeriodicTaskParam | null {
    for (const i in this.taskForm.controls) {
      this.taskForm.controls[i].markAsDirty();
      this.taskForm.controls[i].updateValueAndValidity();
    }
    if (this.taskForm.valid) {
      const task: PeriodicTaskParam = this.taskForm.value;
      task.tags = this.adderTags.toString();
      return task;
    }
    return null;
  }

}
